--[[
fetch upstream server and save
--]]

package.path = './lua/zk/?.lua;' .. package.path
ngx.log(ngx.ERR, 'upstream_fetcher.lua start')


local myutils = require('myutils')
local request = require('request')
local response = require('response')
local sock = require('socket')

local _host = 'localhost'
local _port = 2181

local start1 = socket.gettime() * 1000
local startCpu = os.clock() -- os.clock function returns the number of seconds of CPU time for the program

local _status = {
  xid = 0,
  lastZxidSeen = 0, -- Uint8Array[8]
  timeOut = 30000,
  sessionId = 0, -- Uint8Array[8]
  passwd = myutils.makeBuffer(16) -- Uint8Array[16]
}

local reqConnect = request:new("ConnectRequest", nil, {
  protocolVersion = 0,
  lastZxidSeen = _status.lastZxidSeen,
  timeOut = _status.timeOut,
  sessionId = _status.sessionId,
  passwd = _status.passwd
})
--print(type(req1))
--myutils.printTbl(req1.payload)
--myutils.writeFile(req1:toStream())



local conn = assert(sock.connect(_host, _port))

function sendByteAndWaitResponse(req, responseType)
  conn:send(req:toStream())
  local bytes = conn:receive(4)
  --myutils.writeFile(b1)
  local length = response.unpackInt(bytes)
--  print(responseType .. ', length=' .. length)
  local bytes = conn:receive(length)
  myutils.writeFile(bytes)
  local resp = response:new(responseType, bytes)
  resp:parse()
  return resp
end


local respConnect = sendByteAndWaitResponse(reqConnect, "ConnectResponse")
_status.timeout = respConnect.payload.timeout
_status.sessionId = respConnect.payload.sessionId
_status.passwd = respConnect.payload.passwd


-- -- send get children request
-- local start2 = socket.gettime() * 1000
-- print("phase GetChildren2Request")
-- _status.xid = _status.xid + 1
-- local header = { xid = _status.xid, type = request.OP_CODES.GET_CHILDREN2 }
-- local payload = { path = _path, watch = 0 }
-- local reqChildren = request:new("GetChildren2Request", header, payload)
-- --req2:toStream()
-- --myutils.writeFile(req2:toStream())

-- local respChildren = sendByteAndWaitResponse(reqChildren, "getChildren2Response")
-- for k, v in pairs(respChildren.payload.children) do
--   print("child[" .. k .. "]=" .. v)
-- end


-- -- 解析，然后读取 child/provider的children
-- local toFetch = {}
-- for _, aPath in pairs(respChildren.payload.children) do
--   if string.match(string.lower(aPath), 'rest') then
--     local p = '/dubbo/' .. aPath .. '/providers'
-- --    print('======children:' .. p)
--     local header = { xid = _status.xid, type = request.OP_CODES.GET_CHILDREN2 }
--     local payload = { path = p, watch = 0 }
--     local reqChildren = request:new("GetChildren2Request", header, payload)
--     local respChildren = sendByteAndWaitResponse(reqChildren, "getChildren2Response")
--     for k, v in pairs(respChildren.payload.children) do
--       --      print("child[" .. k .. "]=" .. v)
--       local restApi = myutils.parseDubboRest(v)
-- --      if restApi then
-- --        for kk, vv in pairs(restApi) do print(kk .. '=' .. vv) end
-- --      end
--     end
--     table.insert(toFetch, { path = q, response = respChildren })
--   else
--     print(aPath .. ' not rest, pass')
--   end
-- end

ngx.log(ngx.ERR, "cpu clock = " .. (os.clock() - startCpu))
ngx.log(ngx.ERR, "time used = " .. (socket.gettime() * 1000 - start1))
-- print("query used = " .. (socket.gettime() * 1000 - start2))


conn:close()